package com.you.redisqueue.task;

import com.alibaba.fastjson.JSON;
import com.you.redisqueue.constant.RedisKey;
import com.you.redisqueue.consumer.RedisConsumer;
import com.you.redisqueue.producer.RedisProducer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.LinkedList;
import java.util.List;

/**
 * 业务处理类 定时拉取redis上的失败队列
 *
 * @Author: weiwei.you
 * @Date: 2020-11-13 20:14
 */

@Component
@Slf4j
public class FailBusinessDeal implements Runnable {

    @Autowired
    private RedisConsumer redisConsumer;

    @Autowired
    private RedisProducer redisProducer;


    /**
     * 轮询器，每1分钟请求一次拉取
     **/
    @Scheduled(fixedDelay = 1000 * 60)
    @Override
    public void run() {
        List<Object> list = redisConsumer.getAllData(RedisKey.FAIL_QUEUE);
        if (CollectionUtils.isEmpty(list)) {
            return;
        }
        deal(list);
    }

    /**
     * 处理业务逻辑
     *
     * @param
     */
    private void deal(List<Object> list) {
        List<Object> failArray = new LinkedList<>();
        list.stream().forEach(o -> {
            try {

                // TODO 处理业务逻辑

            } catch (Exception e) {
                log.error("此次任务失败 失败的对象为：{}", e, JSON.toJSONString(o));
                failArray.add(o);
            }
        });

        // 将失败的任务重新扔回失败队列
        redisProducer.putList(RedisKey.FAIL_QUEUE,failArray );

    }
}
